package com.dctp.ems.handler;

import com.jfinal.handler.Handler;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthHandler extends Handler {

    // 登录白名单
    private static final String[] WHITE_LIST = {
        "/ems/admin/login",
    };

    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        // 白名单放行
        for (String white : WHITE_LIST) {
            if (target.equals(white) || target.startsWith(white + "/")) {
                next.handle(target, request, response, isHandled);
                return;
            }
        }

        String token = null;
        // 1. header: token 或 authorization: Bearer xxx
        token = request.getHeader("token");
        if (StrKit.isBlank(token)) {
            String auth = request.getHeader("authorization");
            if (StrKit.notBlank(auth) && auth.toLowerCase().startsWith("bearer ")) {
                token = auth.substring(7).trim();
            }
        }

        // 2. cookie: authorized-token
        if (StrKit.isBlank(token) && request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if ("authorized-token".equals(cookie.getName())) {
                    try {
                        // 解码，提取 accessToken
                        String val = java.net.URLDecoder.decode(cookie.getValue(), "UTF-8");
                        // 只解析 {"accessToken": "xxx", ...}
                        int start = val.indexOf("\"accessToken\":");
                        if (start >= 0) {
                            int quoteStart = val.indexOf("\"", start + 14);
                            int quoteEnd = val.indexOf("\"", quoteStart + 1);
                            if (quoteStart >= 0 && quoteEnd > quoteStart) {
                                token = val.substring(quoteStart + 1, quoteEnd);
                            }
                        }
                    } catch (Exception ignore) {}
                }
            }
        }

        // 3. 没有token
        if (StrKit.isBlank(token)) {
            response.setStatus(401);
            renderJson(response, "{\"code\":401, \"msg\":\"请先登录\", \"redirect\":\"/login\"}");
            isHandled[0] = true;
            return;
        }

        // 4. 查数据库
        Record admin = Db.findFirst("select * from card_enterprise_admin where token=?", token);
        if (admin == null) {
            response.setStatus(401);
            renderJson(response, "{\"code\":401, \"msg\":\"登录已失效，请重新登录\", \"redirect\":\"/login\"}");
            isHandled[0] = true;
            return;
        }

        // 5. 注入当前登录用户到 request，供 Controller 使用
        request.setAttribute("admin", admin);

        // 6. 放行
        next.handle(target, request, response, isHandled);
    }

    private void renderJson(HttpServletResponse response, String json) {
        try {
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().write(json);
            response.getWriter().flush();
        } catch (Exception ignore) {}
    }
}
